import { Space, Button, message, Modal, Breadcrumb, Table, Cascader, TableProps } from 'antd';
import React, { FC } from 'react';
import { DownOutlined } from '@ant-design/icons';
import {
  type FormPanelObject,
  InputType,
  RuleType,
  ExtendReader,
  FormPanel,
  FormPanelBtnAlign,
  Utils,
} from 'lfun-bg-comp';
import _ from 'lodash';
import { useNavigate } from 'react-router';
import {
  HIGHEST_EDUCATION,
  POSITION_LEVEL,
  POSITION_TYPE,
  STAFFING_ARRANGEMENT,
  STAFF_SOURCE,
  STAFF_TYPE,
  TCHR_CHANGE_RESON_TYPE,
} from '@/constant/teachOptions';
import { SearchTransactionParams, Transaction, searchTransaction } from '@/service/teacher/transaction';
import { PageParams } from '@/service';
import { ID_TYPE, POLITICAL_STATUS } from '@/constant/studentOptions';
import { GENDER, YES_NO } from '@/constant/basicOptions';
import { searchSchoolOptions } from '@/service/options';
import { TeachersSrv } from '@/service/teacher';
import { getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
import { PageContainer } from '@/component/page-container';
import { PAGINATIONCONFIG } from '@/constant/page';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';
import { countries } from '@/constant/country';

const Groups: FC = () => {
  const [dataSource, setDataSource] = React.useState<Transaction[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState<FormPanelObject>();
  const [expand, setExpand] = React.useState(false);
  const navigator = useNavigate();
  const country = useCountry();

  const searchList = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '类型',
          name: 'teacher_type',
          key: 'teacher_type',
          inputType: InputType.select,
          renderOption: [],
        },
        { label: '教职工编码', name: 'teacher_number', key: 'teacher_number' },
        { label: '姓名', name: 'teacher_name', key: 'teacher_name' },
        {
          label: '性别',
          name: 'teacher_gender',
          key: 'teacher_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '国籍/地区',
          name: 'nationality',
          key: 'nationality',

          inputType: InputType.select,
          renderOption: countries,
        },
        { label: '手机号', name: 'teacher_phone', key: 'teacher_phone' },
        {
          label: '身份证件类型',
          name: 'teacher_id_type',
          key: 'teacher_id_type',
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '身份证号码',
          name: 'teacher_id_number',
          key: 'teacher_id_number',
        },
        {
          label: '政治面貌',
          name: 'political_status',
          key: 'political_status',
          inputType: InputType.select,
          renderOption: POLITICAL_STATUS,
        },
        {
          label: '最高学历',
          name: 'highest_education',
          key: 'highest_education',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: HIGHEST_EDUCATION,
        },
        {
          label: '出生日期',
          name: 'certificate_issue_date',
          key: 'certificate_issue_date',
          inputType: InputType.date,
          inputProps: {
            picker: 'month',
          },
        },
        {
          label: '教职工来源',
          name: 'source_of_staff',
          key: 'source_of_staff',

          inputType: InputType.children,
          children: <Cascader />,
          renderOption: STAFF_SOURCE,
        },
        {
          label: '是否在编',
          name: 'in_post',
          key: 'in_post',

          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '用人形式',
          name: 'employment_form',
          key: 'employment_form',

          inputType: InputType.select,
          renderOption: STAFFING_ARRANGEMENT,
        },
        {
          label: '教师资格证',
          name: 'employment_form_type',
          key: 'employment_form_type',
          inputType: InputType.select,
          renderOption: STAFFING_ARRANGEMENT,
        },
        {
          label: '是否县级及以上骨干教师',
          name: 'county_level_backbone',
          key: 'county_level_backbone',

          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '教职工类别',
          name: 'staff_category',
          key: 'staff_category',
          inputType: InputType.select,
          renderOption: () => {
            // todo: 这里要区分学校类型数据
            return STAFF_TYPE.ZXX;
          },
        },
        {
          label: '现任岗位类型',
          name: 'current_post_type',
          key: 'current_post_type',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: POSITION_TYPE, //TODO:类型无
        },
        {
          label: '现任岗位等级',
          name: 'current_post_level',
          key: 'current_post_level',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: POSITION_LEVEL,
        },
        {
          label: '是否新教职工',
          name: 'is_new_staff',
          key: 'is_new_staff',
          inputType: InputType.select,
          renderOption: YES_NO,
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '教职工编码',
      dataIndex: 'teacher_number',
      key: 'teacher_number',
    },
    {
      title: '姓名',
      dataIndex: 'teacher_name',
      key: 'teacher_name',
    },
    {
      title: '性别',
      dataIndex: 'teacher_gender',
      key: 'teacher_gender',
      render: (text, record) => {
        if (text) return _.find(GENDER, { value: String(text) })?.label;
        return text;
      },
    },
    {
      title: '教职工号',
      dataIndex: 'teacher_number',
      key: 'teacher_number',
    },
    {
      title: '类型',
      dataIndex: 'teacher_number',
      key: 'teacher_number',
    },
    {
      title: '手机号',
      dataIndex: 'teacher_number',
      key: 'teacher_number',
    },
    // {
    //   title: '身份证件类型',
    //   dataIndex: 'teacher_id_type',
    //   key: 'teacher_id_type',
    //   render: (text, record) => {
    //     if (text) return _.find(ID_TYPE, { value: String(text) })?.label;
    //     return text;
    //   },
    // },
    {
      title: '身份证号码',
      dataIndex: 'teacher_id_number',
      key: 'teacher_id_number',
    },
    {
      title: '任职单位',
      dataIndex: 'school_name',
      key: 'school_name',
    },
    {
      title: '所在地',
      dataIndex: 'teacher_district',
      key: 'teacher_district',
      render: (text, record) => {
        if (text) return _.find(country, { value: String(text) })?.label;
        return text;
      },
    },
    // {
    //   title: '变动原因',
    //   dataIndex: 'transaction_type',
    //   key: 'transaction_type',
    //   render: (text, record) => {
    //     if (text) return _.find(TCHR_CHANGE_RESON_TYPE, { value: String(text) })?.label;
    //     return text;
    //   },
    // },
    // {
    //   title: '申请时间',
    //   dataIndex: 'create_at',
    //   key: 'create_at',
    //   render: (text, record) => {
    //     if (text && text.isValid && text.isValid()) return text.format('YYYY-MM-DD');
    //     return text;
    //   },
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'transaction_remark',
    //   key: 'transaction_remark',
    // },
    {
      title: '操作',
      dataIndex: 'operations',
      key: 'operations',
      align: 'center',
      fixed: 'right',
      // hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => navigator(`${getPathRoot()}/alteration/other/details/view`)}>
            查看
          </Button>
          <Button type="link" onClick={() => navigator(`${getPathRoot()}/alteration/other/details/recover`)}>
            恢复在职
          </Button>
          <Button type="link" onClick={() => navigator(`${getPathRoot()}/alteration/other/details/engage`)}>
            延聘
          </Button>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => navigator(`${getPathRoot()}/employed/details/${record.teacher_id}`)}>
              查看
            </Button>
          </PermissionButton>
          {!['internal'].includes(record.transaction_type) && (
            <PermissionButton permission="edit">
              <Button
                type="link"
                onClick={() => {
                  Modal.confirm({
                    title: '恢复在职',
                    content: `是否恢复在职?`,
                    onOk: async () => {
                      const res: any = await TeachersSrv.active(record.teacher_id, record.transaction_id);
                      if (res.success) {
                        message.success('操作成功');
                        searchFunc(pageIndex, pageSize);
                      } else {
                        message.error(res.message || res.details);
                      }
                    },
                  });
                }}
              >
                恢复在职
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  const searchTemplate = () => {
    const inputs = searchList;
    inputs[0].inputs = expand ? inputs[0].inputs : inputs[0].inputs.slice(0, 9);
    return inputs;
  };
  const pageChange = (page: number, pageSize: number) => {
    set_stoge_pz(pageSize);
    searchFunc(page, pageSize);
  };

  const searchFunc = async (page: number, pageSize: number) => {
    setLoading(true);
    const searchval: SearchTransactionParams & PageParams = {
      ...(form ? form.getFieldsValue() : {}),
      page,
      per_page: pageSize,
    };
    const r = await searchTransaction(searchval);
    if (r.success) {
      setDataSource(r?.data?.items?.length > 0 ? r?.data?.items : [{ transaction_type: '11' }]);
      setTotal(r?.data?.total || 0);
      setPageIndex(page);
      setPageSize(pageSize);
    }
    setLoading(false);
  };

  React.useEffect(() => {
    searchFunc(pageIndex, pageSize);
  }, []);

  const buttonsForm = () => {
    return [
      <a
        style={{ fontSize: 12 }}
        onClick={() => {
          setExpand(!expand);
        }}
      >
        <DownOutlined rotate={expand ? 180 : 0} /> {expand ? '收起' : '展开'}
      </a>,
    ];
  };

  return (
    // <PageContainer header={<Breadcrumb items={[{ title: '变动管理' }]} />}>
    <>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        template={searchTemplate()}
        buttons={buttonsForm()}
        onReset={form => {
          form.resetFields();
          searchFunc(pageIndex, pageSize);
        }}
        onLoad={form => {
          setForm(form);
        }}
        onFinish={async formPanelObject => {
          searchFunc(pageIndex, pageSize);
        }}
      />
      <Space style={{ marginBottom: 20 }}>
        <Button type="primary" onClick={() => navigator(`${getPathRoot()}/alteration/other/create`)}>
          发起变动
        </Button>
      </Space>
      <Table
        dataSource={dataSource}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </>
  );
};

export default Groups;
